﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using ISAMonitor.DNSPODAPI;
using ISAMonitor.RESTTool;
using System.IO;
using System.Text.RegularExpressions;

namespace ISAMonitor
{
    public partial class Form1 : Form
    {
        private string filename = "config.txt";
        private datastore myConfig = null;
        private string lastIP;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //检查配置文件，如果不存在不做任何事情
            if(File.Exists(filename))
            {
                string str = File.ReadAllText(filename);
                myConfig = RESTTool.SerializationTool.GetObj<datastore>(str);
            }

            startrun();
        }

        private void startrun()
        {
            if (myConfig!=null)
            {
                //开启追踪线程
                Thread mythread = new Thread(new ThreadStart(Doloop));
                mythread.IsBackground = true;
                mythread.Start();
            }
        }

        private void Doloop()
        {
            while(true)
            {
                //从ip138获取IP地址
                string ip = GetIPFrom138();
                //与lastIP对比
                if (ip != lastIP)
                {
                    //更新dnspod解析
                    bool ret = RefreshDNSPOD(ip);
                    if (ret)
                    {
                        //更新lastIP
                        lastIP = ip;
                    }
                }

                Thread.Sleep(new TimeSpan(0, 0, 60));
            }
        }

        private bool RefreshDNSPOD(string ip)
        {
            bool ret = true;

            DNSPODAPI.DNSPodCommand myCommand = new DNSPodCommand(myConfig.username,myConfig.password);

            foreach(record rc in myConfig.records)
            {
                //var retobj= myCommand.modifyRecordIPAddress(myConfig.domainid, rid, ip);

                var retobj = myCommand.ModifyRecord(myConfig.domainid, rc.id, rc.name, rc.type, rc.line, ip, rc.mx,
                                                    rc.ttl);
                if (retobj.status.code !="1")
                {
                    ret = false;
                    break;
                }
            }

            return ret;
        }

        private string GetIPFrom138()
        {
            //string pagehtml = RESTTool.RESTCommand.htmlGetter(@"http://www.ip138.com/ip2city.asp", "", "gb2312", false,null, null);
            //string ipregex = @"您的IP地址是：\[(?<ip>.*)\]";

            //Regex myRegex = new Regex(ipregex);
            //Match mymatch = myRegex.Match(pagehtml);


            //string ipaddress = mymatch.Groups["ip"].Captures[0].Value;

            string strip = RESTTool.RESTCommand.htmlGetter("http://www.dnspod.com/About/IP", "", "utf-8", false, null, null);

            return  strip.Trim();
        }

        private void btnSetting_Click(object sender, EventArgs e)
        {
            //生成配置文件
            DNSPODAPI.DNSPodCommand myCommand = new DNSPodCommand(txtUserName.Text, txtPassword.Text);
            DomainListRet domainret = myCommand.GetDomainList();

            // records check
            // fixed by naizhao
            if (domainret.status.code != "1")
            {
                MessageBox.Show("用户名和密码出错！");
                return;
            }

            string domainid = domainret.domains.domain[0].id.ToString();
            string domainname = domainret.domains.domain[0].name.ToString();
            
            var recordret = myCommand.GetRecordList(domainid);

            if (null == recordret.records)
            {
                MessageBox.Show("域名"+domainname+"没有数据！");
                return;
            }

            myConfig = new datastore();
            myConfig.username = txtUserName.Text;
            myConfig.password = txtPassword.Text;
            myConfig.domainid = domainid;
            myConfig.records = recordret.records.record;

            //序列化到文件
            string str = RESTTool.SerializationTool.ParseObj(myConfig);
            File.WriteAllText(filename, str);

            startrun();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://p3p3pp3.yo2.cn"); 
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.dnspod.com"); 
        }

        //private void button1_Click(object sender, EventArgs e)
        //{
        //    string str = textBox1.Text;
        //    DomainListRet myret = SerializationTool.GetObj<DomainListRet>(str);


        //}

        //private void button2_Click(object sender, EventArgs e)
        //{
        //    DomainListRet myRet = new DomainListRet();
        //    status myStatus = new status() { code = "code", created_at = "ca", message = "message" };
        //    myRet.status = myStatus;
        //    domain mydomain1 = new domain() { id = 1, name = "name1", records = "rc1", status = "st1" };
        //    domain mydomain2 = new domain() { id = 2, name = "name2", records = "rc2", status = "st2" };

        //    List<domain> myList = new List<domain>();
        //    myList.Add(mydomain1);
        //    myList.Add(mydomain2);
        //    domains mydomain = new domains() { domain = myList };
        //    myRet.domains = mydomain;

        //    string str = SerializationTool.ParseObj(myRet);
        //    textBox1.Text = str;
        //}

        //private void button3_Click(object sender, EventArgs e)
        //{
        //    DNSPODAPI.DNSPodCommand myCommand = new DNSPodCommand(@"gw2008@gmail.com", "1234567");
        //    DomainListRet domainret = myCommand.GetDomainList();

        //    string domainid = domainret.domains.domain[0].id.ToString();

        //    var recordret = myCommand.GetRecordList(domainid);

        //}
    }
}
